package service

import (
	"git.oschina.net/fanbuchi/xgggh/pay/proto/pay"
	wxpay "git.oschina.net/fanbuchi/xgggh/pay/sdk/wxpay"
	rrrmai_config  "git.oschina.net/fanbuchi/xgggh/pay/service/mmpay/rrrmai"
	//"time"
	"git.oschina.net/fanbuchi/xgggh/pay/service/mmpay"
	"strconv"
	"git.oschina.net/fanbuchi/xgggh/pay/service/mmpay/apppay"
	"errors"
	//"git.oschina.net/fanbuchi/xgggh/pay/logging"
	"time"
	"git.oschina.net/fanbuchi/xgggh/pay/service/mmpay/protocol"
	"github.com/satori/go.uuid"
	"strings"
	"git.oschina.net/fanbuchi/xgggh/pay/model"
)

type MmAppPay struct {

}

func (pay * MmAppPay) initPayClient()(*wxpay.Client,error){
	mmpayClient:=wxpay.NewClient(rrrmai_config.AppId,rrrmai_config.MchId,rrrmai_config.ApiKey)
	//证书验证
	err := mmpayClient.WithCert(rrrmai_config.CertFile, rrrmai_config.KeyFile, rrrmai_config.RootcaFile)
	return mmpayClient,err
}
/**
 app支付 统一下单
 */
func (pay *MmAppPay)UnifiedOrder(req *com_xgggh_srv_pay.Pay) (*wxpay.Params,error)  {
	//以后从配置服务器获取
	mmpayClient,err:=pay.initPayClient()
	if err != nil {
		return nil,err
	}
	//参数
	params := make(wxpay.Params)
	// 统一下单
	params.SetString("appid", mmpayClient.AppId)
	params.SetString("mch_id", mmpayClient.MchId)
	nonce:=uuid.NewV1().String()
	nonce=strings.Replace(nonce,"-","",-1)
	params.SetString("nonce_str", nonce)  // 随机字符串
	params.SetString("out_trade_no", strconv.FormatInt(req.Id,10)) // 商户支付号-每次都是唯一
	params.SetString("fee_type", "CNY") //人民币
	params.SetString("body",rrrmai_config.AppName+"-充值")//商品描述 人人人脉-商品名称
	params.SetString("attach",strconv.FormatInt(req.OrderId,10))//附加数据 订单号
	params.SetInt64("total_fee",req.Fee)
	params.SetString("spbill_create_ip","192.168.1.123")
	params.SetString("time_start",time.Now().Format("20060102150405"))
	params.SetString("time_expire",time.Now().Add(time.Minute*10).Format("20060102150405"))
	params.SetString("notify_url",rrrmai_config.Pay_notify_url)
	params.SetString("trade_type",string(mmpay.App))
	//params.SetString("limit_pay","no_credit")
	signResult:=mmpayClient.Sign(params)
	params.SetString("sign",signResult)
	ret, err := mmpayClient.Post(mmpay_apppay_api.UNIFIED_ORDER, params, true)
	if err != nil {
		return nil,err
	}
	//解析微信支付返回的参数
	//map[return_code:FAIL return_msg:签名错误]
	//map[return_msg:OK result_code:SUCCESS return_code:SUCCESS
	//appid:wx34ab44a8222c441f mch_id:1401969102 nonce_str:eZpxbDPRdy7a0DEj
	// sign:DF4EDB73E10F2172DED3B7895939B425
	// prepay_id:wx201712211639134aa06c07880801373284
	// trade_type:APP]
	//协议错误
	if ret["return_code"] ==protocol.FAIL {
		return nil,errors.New(ret["return_msg"])
	}
	//业务错误
	if ret["result_code"] ==protocol.FAIL {
		return nil,errors.New(ret["err_code"]+"-"+ret["err_code_des"])
	}
	//统一下单请求成功
	if ret["return_code"] ==protocol.SUCCESS&&ret["result_code"] ==protocol.SUCCESS {
		return &ret,nil
	}
	return nil,errors.New("wxpay have a error")
}

/**
	微信支付-唤醒支付客户端
 */
func (pay *MmAppPay)AwakenPayApp(req *wxpay.Params) (*com_xgggh_srv_pay.WxAPPPayParams,error) {
	if req ==nil {
		return nil,errors.New("mmpay unifiedOrder error")
	}
	//Sign
	mmpayClient,err:=pay.initPayClient()
	if err != nil {
		return nil,err
	}
	//参数
	params := make(wxpay.Params)
	params.SetString("appid",req.GetString("appid"))
	params.SetString("partnerid",req.GetString("mch_id"))
	params.SetString("prepayid",req.GetString("prepay_id"))
	params.SetString("package","Sign=WXPay")
	params.SetString("noncestr",req.GetString("nonce_str"))
	params.SetString("timestamp",strconv.FormatInt(time.Now().Unix(),10))
	signResult:=mmpayClient.Sign(params)

	wxPayParams:=com_xgggh_srv_pay.WxAPPPayParams{
		Sign:signResult,
		Appid:params.GetString("appid"),
		PartnerId:params.GetString("partnerid"),
		Prepayid:params.GetString("prepayid"),
		Package:params.GetString("package"),
		Noncestr:params.GetString("noncestr"),
		Timestamp:params.GetString("timestamp"),
	}
	return &wxPayParams,nil
}


func (mmpay *MmAppPay)NotifySign(req string) (*model.WxPayRet,error) {
	//
	wxPayRet:=model.WxPayRet{}
	//Sign
	mmpayClient,err:=mmpay.initPayClient()
	if err != nil {
		return nil,err
	}
	//解析返回的内容
	reader:=strings.NewReader(req)
	params:=mmpayClient.Decode(reader)
	//验证协议
	if params.GetString("return_code")==protocol.FAIL {
		return nil,errors.New(params.GetString("return_msg"))
	}

	if params.GetString("return_result")==protocol.FAIL {
		err:= params.GetString("err_code")+"-"+params.GetString("err_code_des")
		return nil,errors.New(err)
	}
	//读取被签名的文件，重新对比签名是正确的
	//data,_:=ioutil.ReadFile("/Users/os/gopath/wxpay.txt")
	//验证签名
	//reader=strings.NewReader(string(data))
	//params= mmpayClient.Decode(params)
	//空数据不参与签名
	signOk:=mmpayClient.CheckSign(params)
	if !signOk {
		return nil,errors.New("resign decode error")
	}
	//插入数据库
	trade_no:=params.GetString("out_trade_no")
	order_id:=params.GetString("attach")
	tradeNo, err := strconv.ParseInt(trade_no, 10, 64)
	if err !=nil{
		return nil,err
	}
	orderId, err := strconv.ParseInt(order_id, 10, 64)
	if err !=nil{
		return nil,err
	}
	wxPayRet.PayId=tradeNo
	wxPayRet.OrderId=orderId//附加数据为订单号
	wxPayRet.Fee=params.GetInt64("total_fee")
	return &wxPayRet,nil
}